package com.pwser.config;

import java.util.HashMap;
import java.util.Map;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

//	@Bean
//	public RedisTemplate<Object, User> userRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
//		RedisTemplate<Object, User> template = new RedisTemplate<Object, User>();
//		template.setConnectionFactory(redisConnectionFactory);
//		Jackson2JsonRedisSerializer<User> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<User>(User.class);
//		template.setDefaultSerializer(jackson2JsonRedisSerializer);
//		return template;
//	}
//	
//	@Bean
//	public RedisCacheManager userCacheManager(RedisTemplate<Object, User> userRedisTemplate) {
//		RedisCacheManager cacheManager = new RedisCacheManager(userRedisTemplate);
//		cacheManager.setUsePrefix(true);
//		return cacheManager;
//	}
//	
	@Bean(name = "redisTemplate")
	public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
		RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
		redisTemplate.setConnectionFactory(redisConnectionFactory);

		redisTemplate.setKeySerializer(keySerializer());
		redisTemplate.setHashKeySerializer(keySerializer());
		redisTemplate.setValueSerializer(valueSerializer());
		redisTemplate.setHashValueSerializer(valueSerializer());

		return redisTemplate;
	}

	@Bean
	@Primary
	public RedisCacheManager cacheManager(RedisTemplate<Object, Object> redisTemplate) {
		RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
//		cacheManager.setDefaultExpiration(60); //缓存60秒过期
//		Map<String, Long> expiresMap = new HashMap<>();
//		expiresMap.put("userCache", 30L);
//		cacheManager.setExpires(expiresMap);
		cacheManager.setUsePrefix(true);
		return cacheManager;
	}

	private RedisSerializer<String> keySerializer() {
		return new StringRedisSerializer();
	}

	private RedisSerializer<Object> valueSerializer() {
		return new GenericJackson2JsonRedisSerializer();
	}

}
